package com.hyt.it.ogt.data.service.pj.impl;

import com.hyt.core.base.BaseServiceImpl;
import com.hyt.it.ogt.data.Constants;
import com.hyt.it.ogt.data.mapper.pj.PjDataSubjectMapper;
import com.hyt.it.ogt.data.model.entity.pj.Subject;
import com.hyt.it.ogt.data.service.pj.IPjDataSubjectService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

/**
 * <p>
 * 评卷科目表 服务实现类
 * </p>
 *
 * @author liuqi
 * @date 2022-06-07
 */
@Service
public class PjDataSubjectServiceImpl extends BaseServiceImpl<PjDataSubjectMapper, Subject> implements IPjDataSubjectService {
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
    private PjDataSubjectMapper pjDataSubjectMapper;

    @Override
    public void saveSubject(String projectId, List<Subject> subjects) {
        for(Subject subject: subjects){
            String subjectId = subject.getSubjectId();
            if(StringUtils.isEmpty(subjectId)){
                continue;
            }
            Subject projectSubject = this.lambdaQuery()
                    .eq(Subject::getProjectId, projectId)
                    .eq(Subject::getSubjectId, subjectId)
                    .eq(Subject::getDelFlag, false)
                    .one();
            if(projectSubject == null){
                subject.setId(null);
                subject.setSubjectId(subjectId);
				saveSubject(subject);
            }else{
                // 有个考生数量，需要更新
                subject.setId(projectSubject.getId());
                subject.setSubjectId(subjectId);
                updateById(subject);
            }
        }
    }

	private void saveSubject(Subject subject) {
		try {
			save(subject);
		} catch (Exception e) {
			Throwable cause = e.getCause();
		    if (cause instanceof SQLIntegrityConstraintViolationException) {
		        String sqlState = ((SQLIntegrityConstraintViolationException) cause).getSQLState();
		        if (Constants.SQLSTATE_23000.equals(sqlState)) {
		        	logger.error("科目表中已存在主键为：【{}】的数据，sqlState：{}", subject.getProjectId() + "_" + subject.getSubjectId(), sqlState);
		        }
		    } else {
		        throw e;
		    }
		}
	}

	@Override
	public List<Subject> selectByProjectId(String projectId) {
		List<Subject> subjects = pjDataSubjectMapper.selectByProjectId(projectId);
        return subjects;
	}
	
	
	/**
     * 更新科目评完状态
     * @param projectId 评卷项目id
     * @param subjectId 评卷科目
     * @param isFinish 是否评完
     */
    @Override
    public void updateSubjectMarkStatus(String projectId, String subjectId, Boolean isFinish) {
        pjDataSubjectMapper.updateSubjectMarkStatus(projectId, subjectId, isFinish);
    }

}
